

package com.xgit.iov.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xgit.iov.admin.mapper.SysRoleDataRuleMapper;
import com.xgit.iov.admin.mapper.SysRoleMapper;
import com.xgit.iov.admin.mapper.SysRoleMenuMapper;
import com.xgit.iov.admin.service.SysRoleService;
import com.xgit.iov.common.core.constant.CacheConstants;
import com.xgit.iov.common.core.entity.SysRole;
import com.xgit.iov.common.core.entity.SysRoleDataRule;
import com.xgit.iov.common.core.entity.SysRoleMenu;
import com.xgit.iov.common.core.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lengleng
 * @since 2019/2/1
 */
@Service
@RequiredArgsConstructor
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

	private final SysRoleMenuMapper sysRoleMenuMapper;

	private final SysRoleDataRuleMapper sysRoleDataRuleMapper;

	private final CacheManager cacheManager;

	/**
	 * 通过用户ID，查询角色信息
	 *
	 * @param userId
	 * @return
	 */
	@Override
	public List findRolesByUserId(Long userId) {
		return baseMapper.listRolesByUserId(userId);
	}


	@Override
	public List listRoles(Long tenantId) {
		if (ObjectUtil.isNull(tenantId)){
			tenantId = SecurityUtils.getUser().getTenantId();
		}
		return baseMapper.listRoles(tenantId);
	}

	/**
	 * 通过角色ID，删除角色,并清空角色菜单缓存、数据权限缓存
	 *
	 * @param ids
	 * @return
	 */
	@Override
	@CacheEvict(value = CacheConstants.MENU_DETAILS, allEntries = true)
	@Transactional(rollbackFor = Exception.class)
	public Boolean removeRoleById(Long[] ids) {
		for (Long id : ids){
			sysRoleMenuMapper.delete(Wrappers
				.<SysRoleMenu>update().lambda()
				.eq(SysRoleMenu::getRoleId, id));
			sysRoleDataRuleMapper.delete(Wrappers
				.<SysRoleDataRule>update().lambda()
				.eq(SysRoleDataRule::getRoleId,id));
		}
		cacheManager.getCache(CacheConstants.DATARULE_DETAILS).clear();
		return this.removeByIds(CollUtil.toList(ids));
	}
}
